import * as Cesium from 'cesium';

export interface GridPoint {
  x: number; // 经度（格子中心）
  y: number; // 纬度（格子中心）
  value: number;
}

export class CesiumGridTool {
  private viewer: Cesium.Viewer;
  private gridEntities: Cesium.Entity[] = [];
  private polylineEntities: Cesium.Entity[] = [];

  constructor(viewer: Cesium.Viewer) {
    this.viewer = viewer; // 保留构造参数，但实际不再用
  }

  // 按图例分段返回颜色，并加不透明度
  private getColorByValue(value: number): Cesium.Color {
    let color: Cesium.Color;
    if (value > 600) {
      color = Cesium.Color.fromCssColorString('#FF0000');
    } else if (value > 500) {
      color = Cesium.Color.fromCssColorString('#FF8000');
    } else if (value > 400) {
      color = Cesium.Color.fromCssColorString('#FFFF00');
    } else if (value > 300) {
      color = Cesium.Color.fromCssColorString('#00FF00');
    } else if (value > 200) {
      color = Cesium.Color.fromCssColorString('#00FFFF');
    } else {
      color = Cesium.Color.fromCssColorString('#0000FF');
    }
    return color.withAlpha(0.2); // 设置不透明度
  }

  // 正方形网格，label位置为左上1/4处
  drawGridByPointsWithRadius(points: GridPoint[], radius: number = 100) {
    this.clearGrid();
    if (!points.length) return;
    const R = 111320; // 1度纬度约等于111320米
    for (const p of points) {
      // 以p.x,p.y为中心扩展
      const latDelta = radius / R;
      const lngDelta = radius / (R * Math.cos((p.y * Math.PI) / 180));
      const west = p.x - lngDelta;
      const south = p.y - latDelta;
      const east = p.x + lngDelta;
      const north = p.y + latDelta;
      const color = this.getColorByValue(p.value);
      const rectangle = Cesium.Rectangle.fromDegrees(west, south, east, north);
      // 计算左上1/4处的经纬度
      const xLeftQuarter = west + (east - west) * 0.25;
      const yTopQuarter = north - (north - south) * 0.25;
      const leftTopQuarterCartesian = Cesium.Cartesian3.fromDegrees(xLeftQuarter, yTopQuarter);
      const entity = window.viewer.entities.add({
        position: leftTopQuarterCartesian,
        rectangle: {
          coordinates: rectangle,
          material: color,
          outline: false // 关闭Cesium自带边框
        },
        label: {
          text: p.value.toString(),
          font: 'bold 20px sans-serif',
          fillColor: Cesium.Color.fromCssColorString('#ffffff'),
          showBackground: false,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          pixelOffset: new Cesium.Cartesian2(0, 0),
          show: true,
          outlineColor: Cesium.Color.BLACK,
          outlineWidth: 2
        }
      });
      this.gridEntities.push(entity);
      // 添加polyline边框
      const corners = [
        [west, south],
        [west, north],
        [east, north],
        [east, south],
        [west, south]
      ];
      const polylinePositions = corners.map(([lng, lat]) => Cesium.Cartesian3.fromDegrees(lng, lat));
      const polylineEntity = window.viewer.entities.add({
        polyline: {
          positions: polylinePositions,
          width: 1,
          material: Cesium.Color.fromCssColorString('#999999')
        }
      });
      this.polylineEntities.push(polylineEntity);
    }
  }

  clearGrid() {
    try {
      const allEntities = [...this.gridEntities, ...this.polylineEntities];
      for (const entity of allEntities) {
        window.viewer.entities.remove(entity);
      }
      this.gridEntities = [];
      this.polylineEntities = [];
    } catch (error) {
      this.gridEntities = [];
      this.polylineEntities = [];
    }
  }

  // 检查是否有网格实体存在
  hasGridEntities(): boolean {
    return this.gridEntities.length > 0 || this.polylineEntities.length > 0;
  }

  // 获取网格实体数量
  getGridEntitiesCount(): number {
    return this.gridEntities.length + this.polylineEntities.length;
  }
}
